package cn.rubbit.load;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;

import cn.rubbit.ApplicationContext;

/**
 * This class is core object in this project.It recorder all of important
 * object, and it is single.
 */
public class DriverFactory {

	private static DriverFactory instance;

	public static DriverFactory getInstance() {
		if (instance == null) {
			instance = new DriverFactory();
		}
		return instance;
	}

	/**
	 * The constructor method load the db and project information in
	 * config.properties file.
	 * */
	private DriverFactory() {
		try {
			URL[] url = null;
			String[] jars = ApplicationContext.getParms(ApplicationContext.DB_JARS).split(";");
			url = new URL[jars.length];
			for (int i = 0; i < jars.length; i++) {
				url[i] = new File(jars[i]).toURI().toURL();
			}
			Connection conn = null;
			String driver = ApplicationContext.getParms(ApplicationContext.DB_DRIVER);
			if (driver != null && !driver.isEmpty()) {
				URLClassLoader ucl = URLClassLoader.newInstance(url, Thread.currentThread().getContextClassLoader());
				Driver d = (Driver) Class.forName(ApplicationContext.getParms(ApplicationContext.DB_DRIVER), true, ucl).newInstance();
				DriverManager.registerDriver(new CustomDriver(d));
				conn = DriverManager.getConnection(ApplicationContext.getParms(ApplicationContext.DB_URL), ApplicationContext.getParms(ApplicationContext.DB_USR), ApplicationContext.getParms(ApplicationContext.DB_PWD));
			}
			ApplicationContext.set(ApplicationContext.DB_OBJECT, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

class CustomDriver implements Driver {
	private Driver driver;

	CustomDriver(Driver d) {
		this.driver = d;
	}

	public boolean acceptsURL(String u) throws SQLException {
		return this.driver.acceptsURL(u);
	}

	public Connection connect(String u, Properties p) throws SQLException {
		return this.driver.connect(u, p);
	}

	public int getMajorVersion() {
		return this.driver.getMajorVersion();
	}

	public int getMinorVersion() {
		return this.driver.getMinorVersion();
	}

	public DriverPropertyInfo[] getPropertyInfo(String u, Properties p) throws SQLException {
		return this.driver.getPropertyInfo(u, p);
	}

	public boolean jdbcCompliant() {
		return this.driver.jdbcCompliant();
	}

	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return this.driver.getParentLogger();
	}
}
